package com.pan.interceptor;

import com.pan.annotation.LoginRequired;
import com.pan.excep.error.AspectException;
import com.pan.tools.RedisTools;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;


public class OrderInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTools redisTools;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        if (!method.isAnnotationPresent(LoginRequired.class))
            return true;
        LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
        String identity = loginRequired.value();
        Predicate<Cookie> isTicketCookie = cookie -> cookie.getName().equals(identity+"Ticket") ;
        Function<Cookie,String> toTicket = cookie -> cookie.getValue();
        Optional<String> optionalTicket= Arrays.stream(request.getCookies()).filter(isTicketCookie).map(toTicket).findFirst();
        if (!optionalTicket.isPresent()){
            throw new AspectException(403,"没有Cookie信息",LoginRequired.class,method);
        }
        if (!redisTools.exists(identity+":"+optionalTicket.get()).getData()){
            throw new AspectException(403,"没有登录信息",LoginRequired.class,method);
        }
        return true;
    }
}
